<template>
  <div class="register-page">
    <div class="register-container">
      <div class="register-card">
        <!-- 注册头部 -->
        <div class="register-header">
                <div class="logo-section">
        <img src="@/assets/logo.png" alt="万象鉴真" class="logo-image">
        <h1 class="logo-text">万象鉴真</h1>
      </div>
          <p class="register-subtitle">创建您的账户</p>
        </div>

        <!-- 注册表单 -->
        <form @submit.prevent="handleRegister" class="register-form">
          <!-- 用户名 -->
          <div class="form-group">
            <label for="username" class="form-label">用户名</label>
            <input
              type="text"
              id="username"
              v-model="registerForm.username"
              class="form-input"
              :class="{ 'error': errors.username }"
              placeholder="请输入用户名（3-20位字符）"
              required
            >
            <span v-if="errors.username" class="error-message">{{ errors.username }}</span>
          </div>

          <!-- 邮箱 -->
          <div class="form-group">
            <label for="email" class="form-label">邮箱</label>
            <input
              type="email"
              id="email"
              v-model="registerForm.email"
              class="form-input"
              :class="{ 'error': errors.email }"
              placeholder="请输入邮箱地址"
              required
            >
            <span v-if="errors.email" class="error-message">{{ errors.email }}</span>
          </div>

          <!-- 手机号 -->
          <div class="form-group">
            <label for="phone" class="form-label">手机号</label>
            <input
              type="tel"
              id="phone"
              v-model="registerForm.phone"
              class="form-input"
              :class="{ 'error': errors.phone }"
              placeholder="请输入手机号"
              required
            >
            <span v-if="errors.phone" class="error-message">{{ errors.phone }}</span>
          </div>

          <!-- 短信验证码 -->
          <div class="form-group">
            <label for="smsCode" class="form-label">短信验证码</label>
            <div class="verification-input">
              <input
                type="text"
                id="smsCode"
                v-model="registerForm.smsCode"
                class="form-input"
                :class="{ 'error': errors.smsCode }"
                placeholder="请输入验证码"
                required
              >
              <button
                type="button"
                @click="sendSmsCode"
                class="verification-btn"
                :disabled="smsCountdown > 0"
              >
                {{ smsCountdown > 0 ? `重新发送(${smsCountdown}s)` : '发送验证码' }}
              </button>
            </div>
            <span v-if="errors.smsCode" class="error-message">{{ errors.smsCode }}</span>
          </div>

          <!-- 密码 -->
          <div class="form-group">
            <label for="password" class="form-label">密码</label>
            <div class="password-input-wrapper">
              <input
                :type="showPassword ? 'text' : 'password'"
                id="password"
                v-model="registerForm.password"
                class="form-input"
                :class="{ 'error': errors.password }"
                placeholder="请输入密码（至少6位）"
                required
              >
              <button
                type="button"
                @click="togglePassword"
                class="password-toggle"
              >
                {{ showPassword ? '🙈' : '👁️' }}
              </button>
            </div>
            <span v-if="errors.password" class="error-message">{{ errors.password }}</span>
          </div>

          <!-- 确认密码 -->
          <div class="form-group">
            <label for="confirmPassword" class="form-label">确认密码</label>
            <div class="password-input-wrapper">
              <input
                :type="showConfirmPassword ? 'text' : 'password'"
                id="confirmPassword"
                v-model="registerForm.confirmPassword"
                class="form-input"
                :class="{ 'error': errors.confirmPassword }"
                placeholder="请再次输入密码"
                required
              >
              <button
                type="button"
                @click="toggleConfirmPassword"
                class="password-toggle"
              >
                {{ showConfirmPassword ? '🙈' : '👁️' }}
              </button>
            </div>
            <span v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</span>
          </div>

          <!-- 服务条款 -->
          <div class="form-group">
            <label class="checkbox-wrapper">
              <input
                type="checkbox"
                v-model="registerForm.agreeTerms"
                class="checkbox"
                required
              >
              <span class="checkbox-label">
                我已阅读并同意
                <a href="#" @click.prevent="showTerms" class="link">《用户服务协议》</a>
                和
                <a href="#" @click.prevent="showPrivacy" class="link">《隐私政策》</a>
              </span>
            </label>
            <span v-if="errors.agreeTerms" class="error-message">{{ errors.agreeTerms }}</span>
          </div>

          <!-- 注册按钮 -->
          <button
            type="submit"
            class="register-btn"
            :disabled="isLoading"
          >
            <span v-if="isLoading" class="loading-spinner"></span>
            {{ isLoading ? '注册中...' : '立即注册' }}
          </button>
        </form>

        <!-- 登录链接 -->
        <div class="login-link">
          <p>已有账户？ <router-link to="/login">立即登录</router-link></p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Register',
  data() {
    return {
      registerForm: {
        username: '',
        email: '',
        phone: '',
        smsCode: '',
        password: '',
        confirmPassword: '',
        agreeTerms: false
      },
      errors: {},
      showPassword: false,
      showConfirmPassword: false,
      isLoading: false,
      smsCountdown: 0,
      smsTimer: null
    }
  },
  methods: {
    togglePassword() {
      this.showPassword = !this.showPassword
    },
    
    toggleConfirmPassword() {
      this.showConfirmPassword = !this.showConfirmPassword
    },
    
    validateForm() {
      this.errors = {}
      
      // 验证用户名
      if (!this.registerForm.username) {
        this.errors.username = '请输入用户名'
      } else if (!this.isValidUsername(this.registerForm.username)) {
        this.errors.username = '用户名只能包含字母、数字、下划线，长度3-20位'
      }
      
      // 验证邮箱
      if (!this.registerForm.email) {
        this.errors.email = '请输入邮箱地址'
      } else if (!this.isValidEmail(this.registerForm.email)) {
        this.errors.email = '请输入有效的邮箱地址'
      }
      
      // 验证手机号
      if (!this.registerForm.phone) {
        this.errors.phone = '请输入手机号'
      } else if (!this.isValidPhone(this.registerForm.phone)) {
        this.errors.phone = '请输入有效的手机号'
      }
      
      // 验证短信验证码
      if (!this.registerForm.smsCode) {
        this.errors.smsCode = '请输入短信验证码'
      } else if (this.registerForm.smsCode.length !== 6) {
        this.errors.smsCode = '请输入6位验证码'
      }
      
      // 验证密码
      if (!this.registerForm.password) {
        this.errors.password = '请输入密码'
      } else if (this.registerForm.password.length < 6) {
        this.errors.password = '密码至少6位'
      } else if (!this.isValidPassword(this.registerForm.password)) {
        this.errors.password = '密码必须包含字母和数字'
      }
      
      // 验证确认密码
      if (!this.registerForm.confirmPassword) {
        this.errors.confirmPassword = '请确认密码'
      } else if (this.registerForm.password !== this.registerForm.confirmPassword) {
        this.errors.confirmPassword = '两次输入的密码不一致'
      }
      
      // 验证服务条款
      if (!this.registerForm.agreeTerms) {
        this.errors.agreeTerms = '请同意用户服务协议和隐私政策'
      }
      
      return Object.keys(this.errors).length === 0
    },
    
    isValidUsername(username) {
      const usernameRegex = /^[a-zA-Z0-9_]{3,20}$/
      return usernameRegex.test(username)
    },
    
    isValidEmail(email) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      return emailRegex.test(email)
    },
    
    isValidPhone(phone) {
      const phoneRegex = /^1[3-9]\d{9}$/
      return phoneRegex.test(phone)
    },
    
    isValidPassword(password) {
      // 密码必须包含字母和数字
      const hasLetter = /[a-zA-Z]/.test(password)
      const hasNumber = /\d/.test(password)
      return hasLetter && hasNumber
    },
    
    async sendSmsCode() {
      if (!this.registerForm.phone) {
        this.errors.phone = '请先输入手机号'
        return
      }
      
      if (!this.isValidPhone(this.registerForm.phone)) {
        this.errors.phone = '请输入有效的手机号'
        return
      }
      
      try {
        // 模拟发送短信验证码
        await this.mockSendSmsAPI()
        
        // 开始倒计时
        this.startSmsCountdown()
        
        alert('验证码已发送到您的手机，请注意查收')
        
      } catch (error) {
        alert(error.message || '发送失败，请重试')
      }
    },
    
    async mockSendSmsAPI() {
      return new Promise((resolve) => {
        setTimeout(() => {
          // 模拟发送成功
          resolve({ success: true })
        }, 1000)
      })
    },
    
    startSmsCountdown() {
      this.smsCountdown = 60
      this.smsTimer = setInterval(() => {
        this.smsCountdown--
        if (this.smsCountdown <= 0) {
          clearInterval(this.smsTimer)
        }
      }, 1000)
    },
    
    async handleRegister() {
      if (!this.validateForm()) {
        return
      }
      
      this.isLoading = true
      
      try {
        // 模拟注册API调用
        await this.mockRegisterAPI()
        
        // 注册成功
        alert('注册成功！请登录您的账户')
        
        // 跳转到登录页面
        this.$router.push('/login')
        
      } catch (error) {
        // 注册失败
        this.errors.general = error.message || '注册失败，请重试'
        alert(this.errors.general)
      } finally {
        this.isLoading = false
      }
    },
    
    async mockRegisterAPI() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          // 模拟注册验证
          if (this.registerForm.username === 'admin') {
            reject(new Error('用户名已存在'))
          } else if (this.registerForm.email === 'admin@example.com') {
            reject(new Error('邮箱已被注册'))
          } else if (this.registerForm.smsCode !== '123456') {
            reject(new Error('验证码错误'))
          } else {
            resolve({
              success: true,
              message: '注册成功'
            })
          }
        }, 1500)
      })
    },
    
    showTerms() {
      alert('用户服务协议内容...')
    },
    
    showPrivacy() {
      alert('隐私政策内容...')
    }
  },
  
  beforeUnmount() {
    if (this.smsTimer) {
      clearInterval(this.smsTimer)
    }
  }
}
</script>

<style scoped>
.register-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.register-container {
  width: 100%;
  max-width: 500px;
}

.register-card {
  background: white;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  padding: 30px;
  backdrop-filter: blur(10px);
}

.register-header {
  text-align: center;
  margin-bottom: 20px;
}

.logo-section {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-bottom: 10px;
}

.logo-image {
  width: 88px;
  height: 88px;
  object-fit: contain;
  margin-bottom: 10px;
}

.logo-icon {
  font-size: 32px;
}

.logo-text {
  font-size: 28px;
  font-weight: bold;
  color: #1e3c72;
  margin: 0;
}

.register-subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.register-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.form-input {
  width: 100%;
  padding: 12px 15px;
  border: 2px solid #e1e5e9;
  border-radius: 10px;
  font-size: 16px;
  transition: all 0.3s ease;
  background: #f8f9fa;
}

.form-input:focus {
  outline: none;
  border-color: #1e3c72;
  background: white;
  box-shadow: 0 0 0 3px rgba(30, 60, 114, 0.1);
}

.form-input.error {
  border-color: #dc3545;
}

.password-input-wrapper {
  position: relative;
}

.password-toggle {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  padding: 0;
}

.verification-input {
  display: flex;
  gap: 10px;
}

.verification-input .form-input {
  flex: 1;
}

.verification-btn {
  padding: 12px 20px;
  background: #1e3c72;
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.verification-btn:hover:not(:disabled) {
  background: #2a5298;
}

.verification-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.error-message {
  color: #dc3545;
  font-size: 12px;
  margin-top: 5px;
  display: block;
}

.checkbox-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  cursor: pointer;
}

.checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
  margin-top: 2px;
}

.checkbox-label {
  font-size: 14px;
  color: #666;
  cursor: pointer;
  line-height: 1.4;
}

.link {
  color: #1e3c72;
  text-decoration: none;
  transition: color 0.3s ease;
}

.link:hover {
  color: #ff6b35;
}

.register-btn {
  width: 100%;
  padding: 14px;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.register-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(30, 60, 114, 0.4);
}

.register-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.login-link {
  text-align: center;
  padding-top: 15px;
  border-top: 1px solid #e1e5e9;
}

.login-link p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.login-link a {
  color: #1e3c72;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s ease;
}

.login-link a:hover {
  color: #ff6b35;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .register-page {
    padding: 15px;
  }
  
  .register-card {
    padding: 25px 20px;
  }
  
  .logo-text {
    font-size: 24px;
  }
  
  .verification-input {
    flex-direction: column;
  }
  
  .verification-btn {
    width: 100%;
  }
}
</style> 